﻿const cloud = require("wx-server-sdk");

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

const db = cloud.database();
const _ = db.command;

const normalizeString = value =>
  typeof value === "string" ? value.trim() : "";

const registerActivity = async event => {
  const wxContext = cloud.getWXContext();
  const openID = wxContext.OPENID;

  if (!openID) {
    return { success: false, error: "未获取到用户信息" };
  }

  const activityID = normalizeString(event && event.activityID);
  const rawGroupIDs = Array.isArray(event && event.groupIDs)
    ? event.groupIDs
    : [];
  const registrationFields = Array.isArray(event && event.registrationFields)
    ? event.registrationFields
    : [];

  const groupIDs = Array.from(
    new Set(
      rawGroupIDs
        .map(item => normalizeString(item))
        .filter(Boolean)
    )
  );

  if (!activityID) {
    return { success: false, error: "缺少活动编号" };
  }

  if (groupIDs.length === 0) {
    return { success: false, error: "请选择报名分组" };
  }

  try {
    const activityDoc = await db.collection("Activity_Information")
      .doc(activityID)
      .get();

    if (!activityDoc || !activityDoc.data) {
      return { success: false, error: "未找到活动信息" };
    }
  } catch (error) {
    return { success: false, error: "活动信息查询失败" };
  }

  const groupsRes = await db.collection("Activity_Group_Information")
    .where({ ActivityID: activityID })
    .get();
  const groups = groupsRes.data || [];
  const groupMap = new Map(groups.map(item => [item._id, item]));

  const invalidGroupID = groupIDs.find(id => !groupMap.has(id));
  if (invalidGroupID) {
    return { success: false, error: "存在无效的分组编号" };
  }

  const fieldsRes = await db.collection("Activity_Registration_Information_Fields")
    .where({ ActivityID: activityID })
    .get();
  const fields = fieldsRes.data || [];
  const fieldMap = new Map(fields.map(item => [item._id, item]));
  const requiredFieldIDs = fields
    .filter(item => !item.IsOptional)
    .map(item => item._id);

  const processedFields = registrationFields
    .map(item => ({
      fieldID: normalizeString(item && item.fieldID),
      fieldContent: normalizeString(item && item.fieldContent)
    }))
    .filter(item => item.fieldID && fieldMap.has(item.fieldID));

  for (const fieldID of requiredFieldIDs) {
    const matched = processedFields.find(item => item.fieldID === fieldID);
    if (!matched || !matched.fieldContent) {
      const fieldName = (fieldMap.get(fieldID) && fieldMap.get(fieldID).FieldName) || "必填项目";
      return { success: false, error: `请填写${fieldName}` };
    }
  }

  try {
    const result = await db.runTransaction(async transaction => {
      const existingRes = await transaction.collection("Group_Registration_Information")
        .where({
          OpenID: openID,
          GroupID: _.in(groupIDs)
        })
        .get();

      if (existingRes.data.length > 0) {
        throw new Error("您已经报名该活动");
      }

      for (const groupID of groupIDs) {
        const groupInfo = groupMap.get(groupID);
        const capacity = Number(groupInfo.GroupRegistrationCount) || 0;
        if (capacity > 0) {
          let currentCount = 0;
          try {
            const countRes = await transaction.collection("Group_Registration_Information")
              .where({ GroupID: groupID })
              .count();
            currentCount = countRes.total || 0;
          } catch (countError) {
            const listRes = await transaction.collection("Group_Registration_Information")
              .where({ GroupID: groupID })
              .field({ _id: true })
              .get();
            currentCount = (listRes.data || []).length;
          }
          if (currentCount >= capacity) {
            throw new Error("所选分组名额已满");
          }
        }
      }

      for (const groupID of groupIDs) {
        await transaction.collection("Group_Registration_Information").add({
          data: {
            GroupID: groupID,
            OpenID: openID,
            RegistrationTime: db.serverDate(),
            IsCheckedIn: false,
            CheckInTime: null,
            IsCheckedOut: false,
            CheckOutTime: null,
            IsMessageReminder: false,
            MessageReminderTime: null
          }
        });
      }

      if (processedFields.length > 0) {
        await transaction.collection("Group_Registration_Custom_Fields")
          .where({
            OpenID: openID,
            FieldID: _.in(processedFields.map(item => item.fieldID))
          })
          .remove();

        for (const field of processedFields) {
          await transaction.collection("Group_Registration_Custom_Fields").add({
            data: {
              FieldID: field.fieldID,
              OpenID: openID,
              FieldContent: field.fieldContent
            }
          });
        }
      }

      return { success: true };
    });

    return result;
  } catch (error) {
    return {
      success: false,
      error: error.message || "数据库操作失败"
    };
  }
};

exports.main = async (event, context) => {
  return registerActivity(event, context);
};
